<!--
 * @Descripttion: 
 * @version: 
 * @Author: ck
 * @Date: 2021-05-08 11:05:45
 * @LastEditors: ck
 * @LastEditTime: 2021-06-04 10:58:03
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        var sendReq = function () {
            return new Promise((resolve, reject) => {
                let xhr = new XMLHttpRequest();
                xhr.open('post', 'https://www.imooc.com/search/hotwords', true)
                xhr.responseType = 'json';
                xhr.addEventListener('load', function (e) {
                    resolve(this.response)
                })
                xhr.send();
            })
        };

        // await 只能在 async 函数内部中使用
        // await 操作符用于等待一个Promise 对象
        // async函数 默认返回一个Promise对象,因此需要用then获取响应值
        let getData = async function () {
            let data = await sendReq();
            //ajax返回的数据
            return data;
        }

        getData().then(function (result) {
            console.log(result)
        })




        var sendReq = function (url) {
            return new Promise((resolve, reject) => {
                let xhr = new XMLHttpRequest();
                xhr.open('post', url || 'https://www.imooc.com/search/hotwords', true)
                xhr.responseType = 'json';
                xhr.addEventListener('load', function (e) {
                    reject(this.response)
                })
                xhr.send();
            })
        };


        let getData2 = async function () {
            let data = await sendReq();
            //ajax返回的数据
            return data;
        };

        getData2().catch(error => {
            alert('拒绝：' + error);
        });

        let getData3 = async function () {
            let data = await sendReq();
            //返回拒绝状态的promise
            return Promise.reject('rejected Object');
        }

        getData3().catch(error => {
            alert('拒绝3：' + error);
        });


        let getData4 = async function () {
            try {
                //返回拒绝状态，需要捕获异常
                let data = await Promise.reject('拒绝');
            } catch (e) {
                console.log(e);
            }

        };

        getData4();

        let getData5 = async function () {
            try {
                //接口异常，也要捕获
                let data = await sendReq('http:192.168.12.100:8090/api/form');
            } catch (e) {
                alert('ajax异常')
            }
        };

        getData5();



        let getData6 = async function () {
            return await Promise.reject('拒绝');
        };

        //无法在调用处捕获
        try {
            getData6();
        } catch (e) {
            alert('调用处捕获')
        }
    </script>
</body>

</html>